package com.jie.common.http.entity.request;

import com.jie.common.http.constant.HttpCharacterConstant;
import com.jie.common.http.constant.HttpVersionConstant;
import com.jie.common.http.constant.request.HttpRequestMethodConstant;

import java.nio.charset.StandardCharsets;

/**
 * 请求行
 * @author XieZhiJie
 * @date 2022/04/21 16:19
 */
public class HttpRequestLine {

    /**
     * 默认都为post
     */
    private String method;

    private String url = "/";

    /**
     * 默认都为http1.1
     */
    private String httpVersion;

    public HttpRequestLine() {

    }

    public HttpRequestLine(String url) {
        this(HttpRequestMethodConstant.METHOD_POST, url, HttpVersionConstant.HTTP_VERSION_1_1);
    }

    public HttpRequestLine(String method, String url, String httpVersion) {
        this.method = method;
        this.url = url;
        this.httpVersion = httpVersion;
    }

    public String getUrl() {
        return this.url;
    }

    /**
     * 将当前对象的数据转为字节数组
     * @return 返回一个字节数组
     */
    public byte[] getBytes() {
        // 虽然这里用UTF-8, 但是因为请求行基本都是全英, 又因为UTF8的特性,
        // 最后转化的byte数组全都是ascii码
        return toString().getBytes(StandardCharsets.UTF_8);
    }

    /**
     * 从bytes数组中取出对应数据封装到请求行中
     * @param bytes      字节数组
     * @param bytesIndex 字节数组开始索引
     * @return           返回取完行数据后的字节数组结束索引
     */
    public int addHeaderLine(byte[] bytes, int bytesIndex) {
        char eof = HttpCharacterConstant.LINE_FEED;
        char sep = HttpCharacterConstant.HEADER_LINE_SEPARATE;
        byte b = bytes[bytesIndex];
        while (b != eof) {
            int startIndex = bytesIndex;
            while (b != sep) {
                b = bytes[++bytesIndex];
            }
            this.method = new String(bytes, startIndex, bytesIndex - startIndex);
            b = bytes[++bytesIndex];
            startIndex = bytesIndex;
            while (b != sep) {
                b = bytes[++bytesIndex];
            }
            this.url = new String(bytes, startIndex, bytesIndex - startIndex);
            b = bytes[++bytesIndex];
            startIndex = bytesIndex;
            while (b != eof) {
                b = bytes[++bytesIndex];
            }
            this.httpVersion = new String(bytes, startIndex, bytesIndex - startIndex);
        }
        return bytesIndex;
    }

    @Override
    public String toString() {
        return this.method + " " + this.url + " " + this.httpVersion + "\r\n";
    }

}
